﻿using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApplication3.Data;
using WebApplication3.Model;

namespace WebApplication3.Data
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public UserController(ApplicationDbContext context)
        {
            _context = context;
        }

        [HttpPost("login")]
        public IActionResult Login([FromBody] LoginRequest request)
        {
            if (request == null || string.IsNullOrEmpty(request.UserId) || string.IsNullOrEmpty(request.Password))
            {
                return BadRequest(new { code = 400, message = "Invalid request." });
            }

            var user = _context.User.FirstOrDefault(u => u.UserId == request.UserId && u.Password == request.Password);

            if (user == null)
            {
                return Unauthorized(new { code = 401, message = "Invalid user ID or password." });
            }

            return Ok(new
            {
                code = 200,
                data = new
                {
                    id = user.Id,
                    userid = user.UserId,
                    password = user.Password,
                    username = user.Username
                }
            });
        }

        public class LoginRequest
        {
            public string UserId { get; set; }
            public string Password { get; set; }
            public string Username { get; set; }
            public string Id { get; set; }
        }
    }
}
